package com.itic.mall.mobile.uc.address;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.user.persistence.model.MallUser;
import com.itic.mall.system.useraddress.persistence.model.UserAddress;
import com.itic.mall.system.useraddress.persistence.model.UserAddressExample;
import com.itic.mall.system.useraddress.persistence.model.UserAddressExample.Criteria;
import com.itic.mall.system.useraddress.service.UserAddressService;


/**
 * 用户收货地址接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/uc/address")
public class MallUcAddressInterface
     extends BaseMobileInterface {
   
	@Autowired
	private UserAddressService userAddressService;
	
    /**
     * 用户展示所有的收货地址列表信息
     * @return
     */
    @RequestMapping(value="/list")
    @ResponseBody
    public Map<String,Object> list( HttpServletRequest request, HttpServletResponse response, String token){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				UserAddressExample example = new UserAddressExample();
    				example = this.handlePageQuery(request, example);//添加分页
    				example.setOrderByClause("create_time desc");//按创建时间倒序
    				example.setOrderByClause("is_main desc");//默认地址放在前面
    				Criteria criteria = example.createCriteria();
    				criteria.andIsEffectiveEqualTo(DBConst.TRUE);//是否有效标识
    				criteria.andUserIdEqualTo(user.getId());//过虑用户的地址信息
    				example = this.handlePageQuery(request, example);//过虑分页参数
    				int count = userAddressService.count(example);//统计总记录数
    				List<UserAddress> list = userAddressService.list(example);//查找满足条件的数据
    				
    				//封装返回的数据
    				Map<String, Object> dataMap = new HashMap<String,Object>();
	            	dataMap.put("count", count+"");//总记录数
	            	dataMap.put("listData", list);//记录信息
	            	resultMap.put(DATA, dataMap);
    				result = SUCCESS;
        			errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG;  	
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallUcAddressInterface", "list", e.toString(),"用户地址列表",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    /**
     * 用户添加收货地址信息(此方法涉及到中文，必须用POST方式提交)
     * @return 
     */
    @RequestMapping(method= RequestMethod.POST,value="/add")
    @ResponseBody
    public Map<String,Object> add( HttpServletRequest request, HttpServletResponse response, String token, UserAddress address){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(address.getAddressPhone()) && StringHelper.isNotBlank(address.getAddressName())){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				address.setUserId(user.getId());
    				String addResult = "";
    				//用户是否设置为默认地址
    				String isMain = address.getIsMain();
    				if( "1".equals(isMain) ){//用户设置当前添加的地址为默认地址，将其它的地址设置为普通
    					//添加6个必填字段
    					address.setId(IdGen.uuid());
    					address.setIsEffective(DBConst.TRUE);
    					address.setCreateTime(new Date());
    					address.setUpdateTime(new Date());
    					address.setOrgCode(ORG_CODE);
    					address.setCreateUser(CREATE_USER);
    					
    					addResult = userAddressService.addMainAddress(address);
    				}else{
    					address.setIsMain("0");
    					addResult = userAddressService.add(address);
    				}
    				if( SUCCESS.equals(addResult) ){
    					result = SUCCESS;
            			errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG; 
    				}
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallUcAddressInterface", "add", e.toString(),"地址添加",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    /**
     * 用户编辑收货地址（此方法涉及到中文，必须用POST方式提交)
     * @return
     */
    @RequestMapping(method= RequestMethod.POST,value="/view")
    @ResponseBody
    public Map<String,Object> view( HttpServletRequest request, HttpServletResponse response, String id ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(id)  ){
    			UserAddress address = userAddressService.get(id);
				if( null != address ){
					resultMap.put(DATA, address);
					result = SUCCESS;
        			errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG; 
				}else{
					errorCode = ADDRESS_EMPTY_ERROR_CODE;
                	errorMsg = ADDRESS_EMPTY_ERROR_MSG; 
				}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallUcAddressInterface", "edit", e.toString(),"地址编辑",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    
    /**
     * 用户编辑收货地址（此方法涉及到中文，必须用POST方式提交)
     * @return
     */
    @RequestMapping(method= RequestMethod.POST,value="/edit")
    @ResponseBody
    public Map<String,Object> edit( HttpServletRequest request, HttpServletResponse response, String token, UserAddress address){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(address.getId()) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				address.setUserId(user.getId());
    				
    				String editResult = "";
    				String isMain = address.getIsMain();
    				if( "1".equals(isMain) ){
    					editResult = userAddressService.editMainAddress(address);
    				}else{
    					editResult = userAddressService.edit(address);
    				}
    				if( SUCCESS.equals(editResult) ){
    					result = SUCCESS;
            			errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG; 
    				}
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallUcAddressInterface", "edit", e.toString(),"地址编辑",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    

	/**
     * 用户展示所有的收货地址列表信息
     * @return
     */
    @RequestMapping(value="/delete")
    @ResponseBody
    public Map<String,Object> delete( HttpServletRequest request, HttpServletResponse response, String token, String id){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(id) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				String deleteResult = "";
    				UserAddress userAddress = userAddressService.get(id);
    				if( "1".equals(userAddress.getIsMain()) ){
    					result = FAIL;
            			errorCode = ADDRESS_MAIN_ERROR_CODE;
                    	errorMsg = ADDRESS_MAIN_ERROR_MSG;  	
    				}else{
    					deleteResult = userAddressService.delete(userAddress);
    				}
    				if( SUCCESS.equals(deleteResult) ){
    					result = SUCCESS;
            			errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG;  	
    				}
    			}else{
    				result = FAIL;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallUcAddressInterface", "delete", e.toString(),"地址删除",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    /**
     * 用户展示所有的收货地址列表信息
     * @return
     */
    @RequestMapping(value="/defaultSet")
    @ResponseBody
    public Map<String,Object> defaultSet( HttpServletRequest request, HttpServletResponse response, String token, String id ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(id) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				UserAddress address = userAddressService.get(id);
    				String isMain = address.getIsMain();
    				if( "1".equals(isMain) ){
    					result = SUCCESS;
    				}else{
    					//将当前的设置为默认，其它 的设置成普通
    					result = userAddressService.setMainAddress(address);
    				}
    				result = SUCCESS;
        			errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG; 
    			}else{
    				result = FAIL;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallUcAddressInterface", "defaultSet", e.toString(),"设置默认收货地址",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    /**
     * 用户展示所有的收货地址列表信息
     * @return
     */
    @RequestMapping(value="/getDefault")
    @ResponseBody
    public Map<String,Object> getDefault( HttpServletRequest request, HttpServletResponse response, String token ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				Map<String, Object> dataMap = new HashMap<String,Object>();
    				String isHaveAddress="0";
    				UserAddressExample example = new UserAddressExample();
    				example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andIsMainEqualTo(DBConst.TRUE).andUserIdEqualTo(user.getId());
    				
    				List<UserAddress> list = userAddressService.list(example);
    				UserAddress userAddress = null;
    				if( list.size() > 0 ){
    					isHaveAddress="1";
    					userAddress =  list.get(0);
    				}
    				dataMap.put("isHaveAddress", isHaveAddress);
    				dataMap.put("mainAddress", userAddress);
    				resultMap.put(DATA, dataMap);
    				
    				result = SUCCESS;
        			errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG; 
    			}else{
    				result = FAIL;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallUcAddressInterface", "getDefault", e.toString(),"获取默认收货地址",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
}